package com.augurit.gzcgwsp.csshlj.web;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.orm.Page;
import org.springside.modules.web.struts2.Struts2Utils;

import com.augurit.common.base.action.BaseAction;
import com.augurit.common.base.action.CrudActionSupport;
import com.augurit.common.util.ExtUtils;
import com.augurit.common.util.lang.DateUtils;
import com.augurit.common.util.lang.StringUtils;
import com.augurit.gzcgwsp.commonex.util.lang.DateUtilsEX;
import com.augurit.gzcgwsp.csshlj.entity.ShljProject;
import com.augurit.gzcgwsp.csshlj.entity.ShljqsBa;
import com.augurit.gzcgwsp.csshlj.form.ShljqsBaForm;
import com.augurit.gzcgwsp.csshlj.service.IShljqsBaService;
import com.augurit.gzcgwsp.smartformCsdlwj.service.ISmartFormShljqsService;
import com.augurit.gzcgwsp.smartformCsdlwj.service.IYwHwXminfoService;
import com.augurit.gzcgwsp.smartformCsdlwj.web.form.ShljqsForm;
import com.augurit.gzcgwsp.wfex.app.doc.IOaDocCodeServiceEX;
import com.augurit.gzcgwsp.wfex.bi.service.IWfBusTemplateServiceEX;
import com.augurit.gzcgwsp.wfex.bi.service.IWfTemplateAttachmentRefServiceEX;
import com.augurit.gzcgwsp.wfex.bi.web.form.WfTemplateAttachmentRefFormEX;
import com.augurit.gzcgwsp.wfex.common.util.WfUtilsEX;
import com.augurit.wf.bi.service.IWfBusTemplateService;
import com.augurit.wf.bi.web.form.WfBusInstanceTaskForm;
import com.augurit.wf.bi.web.form.WfBusTemplateForm;
import com.augurit.wf.client.summary.web.form.WfTaskSummaryForm;
import com.augurit.wf.common.constant.WfConstant;
import com.augurit.wf.common.form.WfBusSaveResult;
import com.augurit.wf.common.service.IWfBusClientService;
import com.augurit.wf.common.service.IWfService;
import com.augurit.wf.common.util.WfUtils;
import com.augurit.wf.common.web.WfBusClientExtAction;

/**
 * 从事陆域城市生活垃圾经营性清扫、收集、运输服务许可审批备案
 * @author Administrator
 *
 */
@SuppressWarnings( { "serial", "unchecked" })
@Results( {
		@Result(name ="printViewZs", location ="/gzcgwsp/shljqs/preViewXkz.jsp"),
		@Result(name ="printViewfb", location ="/gzcgwsp/shljqs/preViewfbba.jsp"),
		@Result(name ="printViewfb2", location ="/gzcgwsp/shljqs/preViewfb2ba.jsp"),
		@Result(name = CrudActionSupport.RELOAD, location = "shljqs-ba.action", type = "redirect"),
		@Result(name = WfConstant.PRINT, location = WfConstant.PRINT_JSP),
		@Result(name = WfConstant.PRINT_DIR, location = WfConstant.PRINT_DIR_JSP),
		@Result(name = CrudActionSupport.INPUT, location = "/gzcgwsp/shljqs/ShljqsBa-input.jsp"),
		@Result(name = "printxkzs", location = "/gzcgwsp/wfex/client/wf-printExcelEx.jsp"),
		@Result(name = "printfb", location = "/gzcgwsp/wfex/client/wf-printExcelEx.jsp"),
		@Result(name = WfConstant.MAKE_DOCUMENT, location = "/gzcgwsp/wfex/client/common/make-rqjyxk-document.jsp") })
public class ShljqsBaAction extends WfBusClientExtAction {
	private static final Logger log=Logger.getLogger(ShljqsBaAction.class);
	@Autowired
	private IOaDocCodeServiceEX oaDocCodeServiceEX;
	@Autowired
	private IWfTemplateAttachmentRefServiceEX wfTemplateAttachmentRefServiceEX;
	@Autowired
	private IWfBusTemplateServiceEX wfBusTemplateServiceEX;
	@Autowired
	private ISmartFormShljqsService smartFormShljqsService;
    @Autowired
    private IWfBusTemplateService wfBusTemplateService;
	@Autowired
	private IShljqsBaService shljqsBaService;	
	@Autowired
	private IWfService wfService;	
	@Autowired
	private IYwHwXminfoService ywHwXminfoService;
	

	private Page<ShljqsBaForm> page = new Page<ShljqsBaForm>(10);
	private Page<ShljqsForm> qspage = new Page<ShljqsForm>(10);
	private Map pageMap = new HashMap();

	private Long id;
	private ShljqsBaForm form;

    /**
     * 保存业务并关联流程实例
     */
    public String wfBusSave() {
    	try{
    		if(!StringUtils.isBlank(form.getQymc())){
    			form.setSqdw(form.getQymc());
    		}
    		WfBusInstanceTaskForm task = this.wfBusSave((IWfBusClientService)shljqsBaService, form, ShljqsBa.class.getSimpleName());    		
    		WfUtils.renderWfBusSaveJson(task, form);
    	}catch (Exception e) {
      		WfUtils.renderWfFailtureJson("请检查输入内容长度是否过大!");
   		}
        return null;
    }
    
    public String wfBusYslTuih() throws Exception {
    	try {
    		shljqsBaService.wfBusYslTuih(form, this.getLoginUser());
			WfBusSaveResult result = new WfBusSaveResult(true, null);
			result.setTask(new WfBusInstanceTaskForm());
			Struts2Utils.renderJson(result);
		} catch (RuntimeException e) {
			e.printStackTrace();
		}
        return null;
    }   

    public String dataList() throws Exception {
        ExtUtils.initPageFromExtGridParam(getRequest(), qspage);
        ShljqsForm qsForm = new ShljqsForm();
        if(form !=null && form.getSqdw()!=null){
        	qsForm.setSqdw(form.getSqdw());
        }
        smartFormShljqsService.search(qspage, qsForm);
		
        renderText(Struts2Utils.getJsonString(qspage, DateUtils.YEAR_MOUTH_DAY_));
        return null;
    }

	/**
	 * 获得办结ID
	 */
    public String getBj() {
    	try{
    		if(form.getYsid()!=null){
    			WfTaskSummaryForm bjform = null ;// 建立新的分页对象
    			bjform = shljqsBaService.getBjsj(form.getYsid().toString(), "shljqssj");
    			if(bjform.getWfBusInstanceId()!=null){
                    getResponse().getWriter().print("exist"+bjform.getWfBusInstanceId());
    			}
    		}
    	}catch (Exception e) {
   		}
        return null;
    }
	/**
	 * 新增或修改
	 */
	@Override
	public String input() throws Exception {
		this.initWfOpinions();
		getRequest().setAttribute("CurrUserName", this.getLoginUser().getUser().getUserName());
		return INPUT;
	}


	/**
	 * 套打副本
	 * @return
	 * @throws Exception
	 */
	public String printFb() throws Exception{
		 try {
	            String tempPath="Templates/printTemplate/csshlj/fbzs.xls";
	            logger.info("打印经营许可证的文件路径"+tempPath);
	           String context=getRequest().getSession().getServletContext().getRealPath("");
	           String inpath=context+File.separator+tempPath;
	           tempPath=this.shljqsBaService.writeFbData(form,context,inpath);
	           getRequest().setAttribute("templateFilePath",tempPath);
	           logger.info("返回设施一览表文件路径"+tempPath);
	       } catch (Exception e) {
	           log.error("转换模版文件出现错误");
	       }
		  return "printfb";
	  }
	/**
	 * 打印查看许可证书
	 * @return
	 */
	public String preViewXkz(){
	  	String taskId=getRequest().getParameter("taskId");
	  	WfBusInstanceTaskForm instance = wfService.getWfBusInstanceTaskById(Long.valueOf(taskId), this.getLoginUserName());
		String activName=instance.getActivityName();
	    getRequest().setAttribute("hjmc", activName);
	    return "printViewZs";
	}
	
	/**
	 * 打印查看副本
	 * @return
	 */
	public String printViewFb(){
		String taskId=getRequest().getParameter("taskId");
	  	WfBusInstanceTaskForm instance = wfService.getWfBusInstanceTaskById(Long.valueOf(taskId), this.getLoginUserName());
		String activName=instance.getActivityName();
		//开始获取项目登记
		List list=this.shljqsBaService.getProjects(form,1,3);
		int size=list.size();
		if(list.size()<3){
			int num=list.size()+1;
			for(int k=0;k<(3-size);k++){
				ShljProject project=new ShljProject();
				project.setRownums("2");
				project.setColnums(num+"");
				list.add(project);
				num++;
			}
		}
		getRequest().setAttribute("projects", list);
	    getRequest().setAttribute("hjmc", activName);
	  return "printViewfb";
	}

	
	/**
	 * 查看副本第二页
	 * @return
	 */
	public String printViewFb2(){
		//开始获取项目登记
		List list=this.shljqsBaService.getProjects(form,4,6);
		List list1=this.shljqsBaService.getProjects(form,7,9);
		int size=list.size();
		int num=list.size()+1;
		if(list.size()<3){
			for(int k=0;k<(3-size);k++){
				ShljProject project=new ShljProject();
				project.setRownums("3");
				project.setColnums(num+"");
				list.add(project);
				num++;
			}
		}
		
		int size1=list1.size();
		int num1=list1.size()+1;
		if(list1.size()<3){
			for(int j=0;j<(3-size1);j++){
				ShljProject project=new ShljProject();
				project.setRownums("4");
				project.setColnums(num1+"");
				list1.add(project);
				num1++;
			}
		}
		getRequest().setAttribute("projects", list);
		getRequest().setAttribute("projects1", list1);
	    getRequest().setAttribute("hjmc", getRequest().getParameter("hjmc"));
	  return "printViewfb2";
	}
	
	/**
     * 制文
     * @return
     * @throws Exception
     */
    public String makeDocument() throws Exception {
        if (StringUtils.isNotBlank(form.getRedHeadFileId())) {
            String redHeadFilePath = wfBusTemplateServiceEX.getPrintTemplatePath(Long.parseLong(form.getRedHeadFileId()));
            form.setRedHeadFilePath(redHeadFilePath);
        }
        String templateCode = getTemplateCode();
        if(templateCode != null && templateCode.trim().length() > 0){
            String printTemplatePath = wfBusTemplateServiceEX.getPrintTemplatePath(templateCode, WfTemplateAttachmentRefFormEX.ZHENGWEN_TEMPLATE_TYPE);
            form.setTemplatePath(printTemplatePath);
            WfTemplateAttachmentRefFormEX wfTemplateAttachmentRefFormEX = (WfTemplateAttachmentRefFormEX)wfTemplateAttachmentRefServiceEX.get(Long.parseLong(form.getZhengwenFileId()));
            String zhengwenPath = wfTemplateAttachmentRefFormEX.getFilePath() + "/" + wfTemplateAttachmentRefFormEX.getFileRealName();
            form.setZhengwenPath(zhengwenPath);
            form.setCurDate(DateUtilsEX.convertDate2Chinese(new Date()));
            form.setCurYear(String.valueOf(Calendar.getInstance().get(Calendar.YEAR)));
            form.setCurSeq(String.valueOf(oaDocCodeServiceEX.getCurSeqAndAddSeq(templateCode, wfTemplateAttachmentRefFormEX.getFileCode(),form.getId())));
            WfUtilsEX.wfBusPrint(form);
            
            BaseAction.getRequest().setAttribute("fileCode", wfTemplateAttachmentRefFormEX.getFileCode());
            BaseAction.getRequest().setAttribute("entityId", form.getId());
            BaseAction.getRequest().setAttribute("templateId", wfTemplateAttachmentRefFormEX.getId());
//            BaseAction.getRequest().setAttribute("busType", OaFawen.class.getSimpleName());
        }
        return WfConstant.MAKE_DOCUMENT;
    }
	
	/**
	 * 窗口导入前检查
	 * @return
	 * @throws Exception
	 */	
	public String checkImportData() throws Exception{
        String id=getRequest().getParameter("id");
        String templateCode=getRequest().getParameter("templateCode");
        //先查询收件材料是否存在
        boolean flag=this.smartFormShljqsService.checkData(templateCode,"项目情况登记表",Long.valueOf(id),null);
        if(flag){
        }else{
            getResponse().getWriter().print("dataNotExist");
        }
	    
	    return null;
	}

	 /**
	  * 窗口收案环节导入数据
	  */
	public String  importData() throws Exception{
		Map map=getMapByRequest(getRequest());
		String contextPath=getRequest().getSession().getServletContext().getRealPath("");
		map.put("contextPath", contextPath);
		map.put("filename", "项目情况登记表");
		String result=this.shljqsBaService.importData(map);
		if(result==null)
			getResponse().getWriter().print("");
		else
			getResponse().getWriter().print(result);
		
		return null;
	}

    /**
     *获取返回后导入的数据
     * @return
     * @throws IOException 
     */
    public String getResultImportData () throws IOException{
    	String id=getRequest().getParameter("id");
       if(StringUtils.isNotBlank(id)){
    	   ShljqsBaForm form=this.shljqsBaService.get(Long.valueOf(id));
    	   String xmmc = "";
/*    	   if(form!=null && form.getXmmc()!=null){
    		   xmmc = form.getXmmc();
    	   }*/
           getResponse().getWriter().print(xmmc);
       }
        return null;
    }
	private  Map getMapByRequest(HttpServletRequest request) {
		Map<String, String> map = new HashMap<String, String>();
		Enumeration enu = request.getParameterNames();
		while(enu.hasMoreElements()) {   
			String paraName = (String)enu.nextElement();   
			String paraValue = request.getParameter(paraName).trim(); 
			if(!"hjmc".equals(paraName) && !"qylxId".equals(paraName)){//当前的环节名称不需要保存
				map.put(paraName, paraValue);
			}
			
		
		}
		return map;
	}
	

	
	/**
	 * 保存副本第二页的项目日期信息
	 * @return
	 * @throws Exception
	 */
	public String saveFb() throws Exception{
		   try {
			    Long lyYwId=form.getYsid();//第一次审批的业务id
				Map map=getMapByRequest(getRequest());
				String[] projectid=getRequest().getParameterValues("projectId");
				String[] xmcontent=getRequest().getParameterValues("xmcontent");
				String[] rownum=getRequest().getParameterValues("rownums");
				String[] colnum=getRequest().getParameterValues("colnums");
				String[] startday=getRequest().getParameterValues("projectstartday");
				String[] endday=getRequest().getParameterValues("projectenday");
				String[] gzsjday=getRequest().getParameterValues("gzsjday");
				map.put("lyYwId",lyYwId);
				List<ShljProject> list=this.setEntity(projectid, xmcontent, rownum,
						colnum, startday, gzsjday, endday, form);
				ywHwXminfoService.saveByMap(map,list);
				
			} catch (Exception e) {
				
			}
			getResponse().getWriter().print("success");
			return null;
	}
	
	//保存第二页的内容
	public String saveFb2() throws Exception{
		getResponse().getWriter().print("success");
		String[] projectid=getRequest().getParameterValues("projectId");
		String[] xmcontent=getRequest().getParameterValues("xmcontent");
		String[] rownum=getRequest().getParameterValues("rownums");
		String[] colnum=getRequest().getParameterValues("colnums");
		String[] startday=getRequest().getParameterValues("projectstartday");
		String[] endday=getRequest().getParameterValues("projectenday");
		String[] gzsjday=getRequest().getParameterValues("gzsjday");
		List<ShljProject> list=this.setEntity(projectid, xmcontent, rownum,
				colnum, startday, gzsjday, endday, form);
		ywHwXminfoService.saveProject(list);
		
		return null;
	}
	
	
	
	/**
	 * 页面的数据转换为项目登记对象
	 * @param projectid
	 * @param xmcontent
	 * @param rownum
	 * @param colnum
	 * @param startday
	 * @param gzsjday
	 * @param endday
	 * @param form
	 */
	private List<ShljProject>  setEntity(String[]projectid,String[] xmcontent,String[] rownum,
			String[] colnum,String[] startday,String[] gzsjday,String endday[],ShljqsBaForm form){
		List<ShljProject> list=new ArrayList<ShljProject>();
		for(int i=0;i<startday.length;i++){
			String starttime=startday[i];
			String id=projectid[i];
			String content=xmcontent[i];
			String row=rownum[i];
			String col=colnum[i];
			String gzsj=gzsjday[i];
			String endtime=endday[i];
			if(StringUtils.isNotBlank(starttime) && StringUtils.isNotBlank(content.trim()) ){
				ShljProject project=null;
				if(StringUtils.isNotBlank(id)){
					project=this.ywHwXminfoService.getProjectById(id);
				}else{
					project=new ShljProject();
				}
				
				project.setBaid(form.getId());
				project.setFid(form.getYsid());
				if(StringUtils.isNotBlank(form.getQybh())){
					project.setQyid(Long.valueOf(form.getQybh()));
				}
				project.setColnums(col);
				project.setRownums(row);
				project.setGzsjday(gzsj);
				project.setStartday(starttime);
				project.setEndday(endtime);
				project.setXmcontent(content.trim());
				list.add(project);
			}
		}
		return list;
		
	}
	
	
	@Override
	public String delete() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String list() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected void prepareModel() throws Exception {			
		if(id!=null){
			form = shljqsBaService.get(id);
		}else{
			form = new ShljqsBaForm();
		}
		if (form.getSqrq() == null) {
			form.setSqrq(new Date());
		}
		if (StringUtils.isBlank(form.getCbyw())) {
            WfBusTemplateForm wfBusTemplateForm = wfBusTemplateService.getByTemplateCode(getTemplateCode());
            if (wfBusTemplateForm != null) {
                form.setCbyw(wfBusTemplateForm.getTemplateName());
            }
        }
		
		if (StringUtils.isBlank(form.getSjr())) {
            form.setSjr(this.getLoginUser().getUser().getUserName());
        }
		
		if (StringUtils.isBlank(form.getCbbm())) {
            form.setCbbm("环卫处");
        }
        try {
            if (form.getSarq() == null) {
                form.setSarq(new Date());
            }
            if (form.getSqrq() == null) {
                form.setSqrq(new Date());
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
	}
	
	

	@Override
	public String save() throws Exception {
		// TODO Auto-generated method stub
		shljqsBaService.save(form);
		return RELOAD;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public ShljqsBaForm getModel() {
		// TODO Auto-generated method stub
		return form;
	}

	public Page<ShljqsBaForm> getPage() {
		return page;
	}

	public void setPage(Page<ShljqsBaForm> page) {
		this.page = page;
	}

}
